package cn.coisini;

import cn.coisini.model.common.log.enums.BusinessType;
import cn.coisini.model.common.log.enums.OperatorType;
import cn.coisini.model.common.log.service.AsyncOperLogService;
import cn.coisini.model.pojo.AsyncOperLog;
import cn.coisini.utils.IdWorker;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

/**
 * @author xiangshaw
 */

// 启动类
@Log4j2
@RequiredArgsConstructor
@ConfigurationPropertiesScan
@SpringBootApplication
public class CoisiniBlogAdmin implements CommandLineRunner {
    @Value("${workId}")
    private int workId;
    @Value("${datacenterId}")
    private int datacenterId;
    private final AsyncOperLogService asyncOperLogService;

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(CoisiniBlogAdmin.class, args);
        //获取访问地址
        Environment environment = context.getBean(Environment.class);
        //environment.getProperty("server.servlet.context-path") 应用的上下文路径，也可以称为项目路径
        // 获取当前IP
        // String host = InetAddress.getLocalHost().getHostAddress();
        String name = environment.getProperty("spring.application.name");
        String host = environment.getProperty("spring.application.url");
        String port = environment.getProperty("server.port");
        String path = environment.getProperty("server.servlet.context-path","");

        log.info("""
        
                启动成功~ 欢迎使用：{}
                访问地址：{}:{}{}
                默认接口文档地址：{}:{}{}/swagger-ui/index.html
                knife4j接口文档地址：{}:{}{}{}
        """,
                name, host, port, path,
                host, port, path,
                host, port, path, environment.getProperty("knife4j.doc-ui.path"));
    }

    /**
     * 分布式ID生成器
     */
    @Bean
    public IdWorker idWorker() {
        return new IdWorker(workId, datacenterId);
    }

    /**
     * 启动时保存启动日志（纪念最初面试时没有回答上来的问题，SpringBoot项目启动怎么给数据库插入一条数据的问题，）
     */
    @Override
    public void run(String... args) throws Exception {
        log.info("应用启动完成，准备插入日志...");
        AsyncOperLog asyncOperLog = new AsyncOperLog();
        asyncOperLog.setId(String.valueOf(new IdWorker().nextId()));
        asyncOperLog.setTitle("Coisini-Blog-Admin启动");
        asyncOperLog.setBusinessType(BusinessType.INSERT.name());
        asyncOperLog.setOperatorType(OperatorType.MANAGE.name());
        asyncOperLogService.save(asyncOperLog);
        log.info("启动日志插入成功！");
    }
}
